import { type MemberContactsResult } from '@/api/contactsMap/types';
import { ContactsTypeEnum, } from '@/enums/contactsEnum';
import { isNumber } from '@/utils/is';

/** 计算显示的距离 */
export function kmUnit(m: number) {
  if (isNumber(m)) {
    return m >= 1000 ? (m / 1000).toFixed(2) + 'km' : parseInt(m.toString()) + 'm';
  } else {
    return '0m';
  }
}

/**
 * @description 根据人脉类型获取不同参数
 * @date 14/02/2023
 * @export
 * @param {ContactsTypeEnum} contactsType
 * @param {string[]} keys key的集合, 等于ContactsType.PERSON 返回key[0], 否则反之
 */
export function isPerson(contactsType: ContactsTypeEnum | undefined, keys: Array<keyof MemberContactsResult>) {
  const iteratee = contactsType === ContactsTypeEnum.PERSON ? keys[0] : keys[1];
  return iteratee;
}

/**
 * @description 计算两个经纬度之间的距离
 * @date 19/03/2024
 * @export
 * @param {number} lat1
 * @param {number} lon1
 * @param {number} lat2
 * @param {number} lon2
 * @returns {*}  {number} km
 */
export function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  const RADIUS = 6371; // 地球半径，单位千米

  // 将经纬度转换为弧度
  const toRadians = (degrees: number): number => {
    return degrees * Math.PI / 180;
  };

  const lat1Rad = toRadians(lat1);
  const lon1Rad = toRadians(lon1);
  const lat2Rad = toRadians(lat2);
  const lon2Rad = toRadians(lon2);

  // 计算经纬度差
  const deltaLat = lat2Rad - lat1Rad;
  const deltaLon = lon2Rad - lon1Rad;

  // 计算距离
  const a = Math.sin(deltaLat / 2) ** 2 +
    Math.cos(lat1Rad) * Math.cos(lat2Rad) *
    Math.sin(deltaLon / 2) ** 2;
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = RADIUS * c;

  return distance;
}